package it.ilgrv.demiurgo.persistence.tables.context;

import it.ilgrv.demiurgo.persistence.tables.character.Level;

import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;

import org.apache.log4j.Logger;

public class ContextWrapper {
	private static final Logger		log				= Logger.getLogger(ContextWrapper.class);

	private static ServletContext	sc;

	private static String			startingXPConf	= "characterStartingXP";
	private static String			defaultCharacterStatusOnCreation	= "defaultCharacterStatusOnCreation";
	private static String			sacrifyPercentageConf				= "sacrifyPercentage";
	private static String			levelsConf							= "levels";
	public static void init(ServletContextEvent sce) {
		sc = sce.getServletContext();
	}

	/**
	 * return the configured value for starting XP point for a character. if not
	 * setted return a default value
	 * 
	 * @return
	 */
	public static int getStartingXP() {
		String value = (String) sc.getAttribute(startingXPConf);
		if (value == null || value.isEmpty()) {
			return 3000;
		}

		try {
			return Integer.parseInt(value);
		} catch (Exception e) {
			return 3000;
		}
	}

	/**
	 * return the id of default character status on creation. it must be setted
	 * 
	 * @return
	 */
	public static Integer getIdOfDefaultCharacterStatusOnCreation() {
		String value = (String) sc.getAttribute(defaultCharacterStatusOnCreation);
		if (value == null || value.isEmpty()) {
			return null;
		}

		try {
			return Integer.parseInt(value);
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * return the configured percentage of XP gained on sacrify. default is
	 * setted as 25
	 * 
	 * @return
	 */
	public static Integer getSacrifyPercentage() {
		String value = (String) sc.getAttribute(sacrifyPercentageConf);
		if (value == null || value.isEmpty()) {
			return 25;
		}

		try {
			return Integer.parseInt(value);
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * get a cached copy of Levels table
	 * 
	 * @return
	 */
	public static List<Level> getLevels() {
		return (List<Level>) sc.getAttribute(levelsConf);
	}
}
